package cn.kgc.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.kgc.base.SystemConstant;
import cn.kgc.entity.Users;
import cn.kgc.excpetion.GraceException;
import cn.kgc.form.UsersUpdateForm;
import cn.kgc.grace.result.GraceJSONResult;
import cn.kgc.grace.result.ResponseStatusEnum;
import cn.kgc.interceptor.JwtInterceptor;
import cn.kgc.service.UsersService;
import cn.kgc.utils.PagedGridResult;
import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author YC
 */
@RestController
@RequestMapping("/users")
@Api(tags = "求职者招聘者用户管理模块")
@Validated
@Slf4j
public class UsersController {

    @Resource
    private UsersService usersService;

    @PostMapping("/admin/userIdList")
    @ApiOperation(value = "根据用户名模糊查询用户id列表")
    public GraceJSONResult userIdList(String userName) {
        List<Users> userList = usersService.list(
                new LambdaQueryWrapper<Users>()
                        .likeRight(Users::getRealName, userName)
                        // 只查询id字段
                        .select(Users::getId)
        );
        return GraceJSONResult.ok(userList);
    }

    @PostMapping("/app/modify")
    @ApiOperation(value = "求职者招聘者修改自己信息")
    public GraceJSONResult modifySelf(@RequestBody UsersUpdateForm form) {
        // 判断登录的用户是否修改自己的信息
        String userId = JwtInterceptor.userIds.get();
        if (form.getId().equals(userId)) {
            GraceException.display(ResponseStatusEnum.USER_INFO_UPDATED_ERROR);
        }
        // 修改用户信息
        Users users = BeanUtil.copyProperties(form, Users.class);
        return GraceJSONResult.ok(usersService.updateById(users));
    }

    @PostMapping("/detail")
    @ApiOperation(value = "求职者招聘者查看自己信息")
    @SentinelResource(value = "userDetail")
    public GraceJSONResult detail(String userId) {
        try {
            Thread.sleep(300);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        String loginUserId = JwtInterceptor.userIds.get();
        return GraceJSONResult.ok(usersService.getById(userId));
    }


    @GetMapping("/selectHrCount")
    @ApiOperation(value = "查询公司HR数量")
    public GraceJSONResult selectHrCount(String companyId) {
        return GraceJSONResult.ok(usersService.getHrCount(companyId));
    }

    @PostMapping("/getCompanyIdByUserId")
    @ApiOperation(value = "根据用户ID查询对应公司ID（如果是HR，不是HR返回空字符串）")
    public GraceJSONResult getCompanyIdByUserId(String userId) {
        Users user = usersService.getOne(
                new LambdaQueryWrapper<Users>().eq(Users::getId, userId)
                        .eq(Users::getRole, SystemConstant.ROLE_JOB_RECRUITERS)
        );
        if (user == null) {
            //如果当前用户还不是招聘者,没有对应的公司的ID
            return GraceJSONResult.ok("");
        }
        //如果是招聘者,返回对应的公司的ID
        return GraceJSONResult.ok(user.getHrInWhichCompanyId());
    }

    @PostMapping("/updateUserRole")
    @ApiOperation(value = "修改用户角色为招聘者")
    public GraceJSONResult updateUserRole(@RequestParam("commitUserId") String commitUserId, @RequestParam("companyId") String companyId) {
        return GraceJSONResult.ok(usersService.updateUserRole(commitUserId, companyId));
    }

    @PostMapping("/admin/hrList")
    @ApiOperation(value = "分页查询用户列表")
    public PagedGridResult hrList(
            @RequestParam(defaultValue = "1") int pageIndex,
            @RequestParam(defaultValue = "10") int pageSize) {
        //获得登录的用户信息
        String s = JwtInterceptor.userIds.get();
        Users users = usersService.getById(s);
        //如果用户是招聘者
        if (users.getRole() == SystemConstant.ROLE_JOB_RECRUITERS) {
            //获得招聘者所在的公司的编号
            String hrInWhichCompanyId = users.getHrInWhichCompanyId();
            //分页查询招聘者所在的公司中所有的HR的信息
            return usersService.hrList(pageIndex, pageSize, hrInWhichCompanyId);
        } else {
            //如果用户不是招聘者,返回空的集合
            return new PagedGridResult();
        }
    }

    @PostMapping("/chanageUserToCand")
    @ApiOperation(value = "HR离职")
    public GraceJSONResult hrDimission() {
        //获得登录的用户信息
        String s = JwtInterceptor.userIds.get();
        Users users = usersService.getById(s);
        if (users.getRole() == SystemConstant.ROLE_JOB_RECRUITERS) {
            users.setRole(SystemConstant.ROLE_JOB_SEEKERS);
            users.setHrInWhichCompanyId("");
            return GraceJSONResult.ok(usersService.updateById(users));
        }
        return GraceJSONResult.errorMsg("您不是HR,无法离职");
    }

}
